const moment = require('moment')
const sendMail = require('../../common/email')
const emailUtil = require('../../util/emailUtil')
const MarketMachine = require('../../analysis/marketMachine')
const { numberUtil } = require('../../util')
const reqlib = require('app-root-path').require
const btbAs = reqlib('/app/common/btb')
/**
 * 获取所有用户
 * @param ctx
 * @returns {Promise<void>}
 */
exports.getUserBtbs = async function (ctx) {
  try {
    const tokenRaw = ctx.tokenRaw
    const userBtbs = await ctx.services.userBtb.getUserBtbs({
      userName: tokenRaw.name
    })
    ctx.body = ctx.resuccess({
      list: userBtbs
    })
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getUserBtb = async function (ctx) {
  const query = ctx.query
  try {
    const tokenRaw = ctx.tokenRaw
    const data = ctx.validateData({
      type: { required: true }
    }, query)
    const userBtb = await ctx.services.userBtb.getUserBtb({
      ...data,
      userName: tokenRaw.name
    })
    ctx.body = ctx.resuccess(userBtb)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

/**
 * 加仓
 * @param ctx
 * @returns {Promise<void>}
 */
exports.addPosition = async function (ctx) {
  const query = ctx.request.body
  try {
    const tokenRaw = ctx.tokenRaw
    const data = ctx.validateData({
      type: { required: true },
      shares: { required: true, type: 'number' }
    }, query)
    await ctx.services.userBtb.addPosition({
      ...data,
      userName: tokenRaw.name
    })
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.cutPosition = async function (ctx) {
  const query = ctx.request.body
  try {
    const tokenRaw = ctx.tokenRaw
    const data = ctx.validateData({
      type: { required: true },
      shares: { required: true, type: 'number' }
    }, query)
    await ctx.services.userBtb.cutPosition({
      ...data,
      userName: tokenRaw.name
    })
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getMyBalanceInfo = async function (ctx) {
  try {
    const res = await ctx.services.btbIndex.getMyBalanceInfo()
    ctx.body = ctx.resuccess(res)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

// 添加
exports.addBtbIndex = async function (ctx) {
  const query = ctx.request.body
  try {
    const data = ctx.validateData({
      name: { required: true, type: 'string' },
      code: { required: true, type: 'string' },
      frequency: { required: true, type: 'string' },
      strategy: { required: true, type: 'string' },
      buy_status: { required: true, type: 'int' },
      sell_status: { required: true, type: 'int' },
      proportion: { required: true, type: 'number' },
      condition_buy_status: { required: true, type: 'int' },
      condition_sell_status: { required: true, type: 'int' },
      condition_buy_number: { required: true, type: 'number' },
      condition_sell_number: { required: true, type: 'number' },
      status: { required: true, type: 'int' },
      xh_status: { required: false, type: 'int' },
      hy_status: { required: false, type: 'int' }
    }, query)
    await ctx.services.btbIndex.addBtbIndex(data)
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.deleteBtbIndex = async function (ctx) {
  const query = ctx.request.body
  try {
    const data = ctx.validateData({
      _id: { required: true, type: 'string' }
    }, query)
    await ctx.services.btbIndex.deleteBtbIndex(data)
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

// 修改
exports.updateBtbIndex = async function (ctx) {
  const query = ctx.request.body
  try {
    const data = ctx.validateData({
      _id: { required: true, type: 'string' },
      code: { required: false, type: 'string' },
      name: { required: false, type: 'string' },
      frequency: { required: false, type: 'string' },
      strategy: { required: false, type: 'string' },
      buy_sell_reason: { required: false, type: 'string' },
      status: { required: false, type: 'int' },
      xh_status: { required: false, type: 'int' },
      hy_status: { required: false, type: 'int' },
      buy_status: { required: false, type: 'int' },
      sell_status: { required: false, type: 'int' },
      proportion: { required: false, type: 'number' },
      condition_buy_status: { required: false, type: 'int' },
      condition_sell_status: { required: false, type: 'int' },
      condition_buy_number: { required: false, type: 'number' },
      condition_sell_number: { required: false, type: 'number' },
      manual: { required: false, type: 'int' },
      blacklist: { required: false, type: 'int' }
    }, query)
    await ctx.services.btbIndex.updateBtbIndex(data)
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.updateBtbStrategy = async function (ctx) {
  const query = ctx.request.body
  try {
    const data = ctx.validateData({
      code: { required: true, type: 'string' },
      strategy: { required: true, type: 'string' }
    }, query)
    await ctx.services.btbIndex.updateBtbIndexByCode(data)
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

// 修改状态
exports.changeBtbIndexStatus = async function (ctx) {
  const query = ctx.request.body
  try {
    const data = ctx.validateData({
      code: { required: true, type: 'string' },
      status: { required: true, type: 'int' },
      xh_status: { required: true, type: 'int' },
      hy_status: { required: true, type: 'int' }
    }, query)
    await ctx.services.btbIndex.changeBtbIndexStatus(data)
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getBtbIndexByPage = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      current: { type: 'int', required: true },
      pageSize: { type: 'int', required: true },
      code: { type: 'string', required: false }
    }, query)
    let paging = ctx.paging(data.current, data.pageSize)
    // 分页获取
    const btbIndex = await ctx.services.btbIndex.getBtbIndexByPage({ code: data.code }, paging)
    paging.total = btbIndex.count
    ctx.body = ctx.resuccess({
      list: btbIndex.list,
      page: paging
    })
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getBtbIndexByCode = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      code: { type: 'string', required: true }
    }, query)
    const btbIndex = await ctx.services.btbIndex.getBtbIndexByCode(data)
    ctx.body = ctx.resuccess(btbIndex)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getBtbIndexAll = async function (ctx) {
  try {
    const btbIndex = await ctx.services.btbIndex.getBtbIndexAll()
    ctx.body = ctx.resuccess(btbIndex)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getBtbIndexWithPosition = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      code: { type: 'string', required: true }
    }, query)
    const btbIndex = await ctx.services.btbIndex.getBtbIndexWithPosition(data)
    ctx.body = ctx.resuccess(btbIndex)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getBtbRecordByPage = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      current: { type: 'int', required: true },
      pageSize: { type: 'int', required: true },
      code: { type: 'string', required: false }
    }, query)
    let paging = ctx.paging(data.current, data.pageSize)
    // 分页获取
    const btbRecord = await ctx.services.btbIndex.getBtbRecordByPage({ code: data.code }, paging)
    paging.total = btbRecord.count
    ctx.body = ctx.resuccess({
      list: btbRecord.list,
      page: paging
    })
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.checkBtbStatusMonth = async function (ctx) {
  try {
    await ctx.services.btbIndex.checkBtbStatusMonth()
    ctx.body = ctx.resuccess()
  } catch (err) {
    console.log(err)
    const btbErrorEmail = await ctx.services.dictionary.getByKey('btbErrorEmail')
    if (btbErrorEmail && btbErrorEmail.value === 'true') {
      await sendMail(emailUtil.sendErrorEmail({
        userEmail: '673806687@qq.com',
        err
      }))
    }
    ctx.body = ctx.refail(err)
  }
}

exports.checkBtbStatusWeek = async function (ctx) {
  try {
    await ctx.services.btbIndex.checkBtbStatusWeek()
    ctx.body = ctx.resuccess()
  } catch (err) {
    console.log(err)
    const btbErrorEmail = await ctx.services.dictionary.getByKey('btbErrorEmail')
    if (btbErrorEmail && btbErrorEmail.value === 'true') {
      await sendMail(emailUtil.sendErrorEmail({
        userEmail: '673806687@qq.com',
        err
      }))
    }
    ctx.body = ctx.refail(err)
  }
}

exports.checkBtbStatusDay = async function (ctx) {
  try {
    await ctx.services.btbIndex.checkBtbStatusDay()
    ctx.body = ctx.resuccess()
  } catch (err) {
    console.log(err)
    // const btbErrorEmail = await ctx.services.dictionary.getByKey('btbErrorEmail')
    // if (btbErrorEmail && btbErrorEmail.value === 'true') {
    //   await sendMail(emailUtil.sendErrorEmail({
    //     userEmail: '673806687@qq.com',
    //     err
    //   }))
    // }
    ctx.body = ctx.refail(err)
  }
}

exports.checkBtbStatus4Hour = async function (ctx) {
  try {
    await ctx.services.btbIndex.checkBtbStatus4Hour()
    ctx.body = ctx.resuccess()
  } catch (err) {
    console.log(err)
    // const btbErrorEmail = await ctx.services.dictionary.getByKey('btbErrorEmail')
    // if (btbErrorEmail && btbErrorEmail.value === 'true') {
    //   await sendMail(emailUtil.sendErrorEmail({
    //     userEmail: '673806687@qq.com',
    //     err
    //   }))
    // }
    ctx.body = ctx.refail(err)
  }
}

// 检查操作
exports.checkBtbStatus1Hour = async function (ctx) {
  try {
    await ctx.services.btbIndex.checkBtbStatus1Hour()
    ctx.body = ctx.resuccess()
  } catch (err) {
    console.log(err)
    const btbErrorEmail = await ctx.services.dictionary.getByKey('btbErrorEmail')
    if (btbErrorEmail && btbErrorEmail.value === 'true') {
      await sendMail(emailUtil.sendErrorEmail({
        userEmail: '673806687@qq.com',
        err
      }))
    }
    ctx.body = ctx.refail(err)
  }
}

// 自动买卖
exports.buySellBtbXH15m = async function (ctx) {
  try {
    await ctx.services.btbIndex.buySellBtbXH15m()
    ctx.body = ctx.resuccess()
  } catch (err) {
    console.log(err)
    await sendMail(emailUtil.sendErrorEmail({
      userEmail: '673806687@qq.com',
      err
    }))
    ctx.body = ctx.refail(err)
  }
}

exports.buySellBtbHY15m = async function (ctx) {
  try {
    const res = await ctx.services.btbIndex.buySellBtbHY15m()
    await ctx.services.dictionary.updateByKey('btbDoneMessage', {
      value: JSON.stringify({
        msg: '成功',
        success: true,
        time: moment().format('YYYY-MM-DD HH:mm:ss'),
        timeCost: (res && res.timeCost) || '',
        timeAnalysis: (res && res.timeAnalysis) || '',
        queryCost: (res && res.queryCost) || '',
        emCost: (res && res.emCost) || '',
        time1: (res && res.time1) || '',
        time2: (res && res.time2) || '',
        time3: (res && res.time3) || '',
        time4: (res && res.time4) || ''
      })
    })
    ctx.body = ctx.resuccess()
  } catch (err) {
    console.log(err)
    await ctx.services.dictionary.updateByKey('btbDoneMessage', {
      value: JSON.stringify({
        msg: '失败',
        success: false,
        time: moment().format('YYYY-MM-DD HH:mm:ss')
      })
    })
    await ctx.services.errMsg.addErrMsg(err)
    const btbErrorEmail = await ctx.services.dictionary.getByKey('btbErrorEmail')
    if (btbErrorEmail && btbErrorEmail.value === 'true') {
      await sendMail(emailUtil.sendErrorEmail({
        userEmail: '673806687@qq.com',
        err
      }))
    }
    ctx.body = ctx.refail(err)
  }
}

// 平仓
exports.closePositionHY = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      code: { type: 'string', required: true }
    }, query)
    await ctx.services.btbIndex.closePositionHY(data)
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.changeLeverage = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      code: { type: 'string', required: true },
      leverage: { type: 'int', required: true }
    }, query)
    await ctx.services.btbIndex.changeLeverage(data)
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

// 平仓
exports.closeAllPositionHY = async function (ctx) {
  try {
    await ctx.services.btbIndex.closePositionHY()
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

// 平仓
exports.closePositionXH = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      code: { type: 'string', required: true }
    }, query)
    await ctx.services.btbIndex.closePositionXH(data)
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

// 平仓
exports.closeAllPositionXH = async function (ctx) {
  try {
    await ctx.services.btbIndex.closePositionXH()
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.quickBuyXH = async function (ctx) {
  try {
    await ctx.services.btbIndex.quickBuyXH()
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

// 检查操作
exports.updateBtbMonitor = async function (ctx) {
  try {
    await ctx.services.btbIndex.updateBtbMonitor()
    ctx.body = ctx.resuccess()
  } catch (err) {
    console.log(err)
    ctx.body = ctx.refail(err)
  }
}

exports.getBtbMonitor = async function (ctx) {
  try {
    const list = await ctx.services.btbIndex.getBtbMonitor()
    ctx.body = ctx.resuccess(list)
  } catch (err) {
    console.log(err)
    ctx.body = ctx.refail(err)
  }
}

exports.getUsdtBtbIndex = async function (ctx) {
  try {
    const btbRecord = await ctx.services.btbIndex.getUsdtBtbIndex()
    ctx.body = ctx.resuccess(btbRecord)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getAssetHY = async function (ctx) {
  try {
    const res = await ctx.services.btbIndex.getAssetHY()
    ctx.body = ctx.resuccess(res)
  } catch (err) {
    console.log(err)
    ctx.body = ctx.refail(err)
  }
}

exports.getExecuteRecordsByPage = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      current: { type: 'int', required: true },
      pageSize: { type: 'int', required: true },
      code: { type: 'string', required: false },
      market: { type: 'int', required: false },
      type: { type: 'string', required: false },
      strategy: { type: 'string', required: false },
      strategy_result: { type: 'string', required: false },
      reason: { type: 'string', required: false },
      searchText: { type: 'string', required: false },
      startTime: { type: 'string', required: false },
      endTime: { type: 'string', required: false },
      incomeType: { type: 'string', required: false },
      addPosition: { type: 'string', required: false },
      lossMany: { type: 'string', required: false }
    }, query)
    let paging = ctx.paging(data.current, data.pageSize)
    // 分页获取
    const result = await ctx.services.executeRecord.getRecordsByPage({
      ...data
    }, paging)
    paging.total = result.count
    ctx.body = ctx.resuccess({
      list: result.list.map((v) => {
        const detail = v.detail || {}
        // btbAs.getAnalysisMarketInfo(detail)
        // detail.canOpenList = []
        // detail.countModel1d = {}
        // detail.countModel1h = {}
        // detail.countModel4h = {}
        // detail.countModel15m = {}
        // detail.countSumModelInfo = {}
        // detail.info1d = {}
        // detail.info1h = {}
        // detail.info4h = {}
        detail.info15m = detail.info15m || {}
        const baseInfo = {
          isIndexCloseNewHigh: detail.isIndexCloseNewHigh || false,
          isIndexCloseNewLow: detail.isIndexCloseNewLow || false,
          buySellRawTotalWalletBalance: detail.buySellRawTotalWalletBalance || false,
          useMaxIndexBuySellPosition: detail.useMaxIndexBuySellPosition || false,
          netChangeRatio15m: detail.info15m.close ? numberUtil.countDifferenceRate(detail.info15m.close, detail.info15m.open) : 0
        }
        v.detail = {}
        v.track_list = v.track_list || []
        let sellReasonCount = 0
        v.track_list.forEach((t) => {
          t.name = t.name || ''
          if (t.name.startsWith('sellIfOnlyPingByReason-')) {
            sellReasonCount++
          }
        })
        v.track_list = []
        return {
          ...v,
          ...baseInfo,
          sellReasonCount
        }
      }),
      page: paging
    })
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getExecuteRecordDetail = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      _id: { type: 'string', required: true }
    }, query)
    const result = await ctx.services.executeRecord.getExecuteRecordDetail(data)
    result.detail = result.detail || {}
    btbAs.getAnalysisMarketInfo(result.detail)
    ctx.body = ctx.resuccess(result)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

// 获取操作统计
exports.getExecuteRecordsStatistics = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      startTime: { type: 'string', required: false }
    }, query)
    const result = await ctx.services.executeRecord.getExecuteRecordsStatistics(data)
    ctx.body = ctx.resuccess(result)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.deleteExpireExecuteRecord = async function (ctx) {
  try {
    const res = await ctx.services.executeRecord.deleteExpireExecuteRecord()
    ctx.body = ctx.resuccess(res)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.deleteExecuteRecords = async function (ctx) {
  try {
    const res = await ctx.services.executeRecord.deleteExecuteRecords()
    ctx.body = ctx.resuccess(res)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.reFormatExecuteRecords = async function (ctx) {
  try {
    const res = await ctx.services.executeRecord.reFormatExecuteRecords()
    ctx.body = ctx.resuccess(res)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.findGoodBtbInMarket = async function (ctx) {
  try {
    await ctx.services.btbIndex.findGoodBtbInMarket()
    await ctx.services.btbIndex.checkBtbStatusDay()
    await ctx.services.btbIndex.getBtbIndexWithDailyBalance()
    ctx.body = ctx.resuccess({})
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.findBtbByAnalysis = async function (ctx) {
  try {
    const result = await ctx.services.btbIndex.findBtbByAnalysis()
    ctx.body = ctx.resuccess(result)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getAssetRecordsByPage = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      current: { type: 'int', required: true },
      pageSize: { type: 'int', required: true }
    }, query)
    let paging = ctx.paging(data.current, data.pageSize)
    // 分页获取
    const result = await ctx.services.assetRecord.getRecordsByPage({
      ...data
    }, paging)
    paging.total = result.count
    ctx.body = ctx.resuccess({
      list: result.list,
      page: paging
    })
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.addAssetRecord = async function (ctx) {
  try {
    await ctx.services.assetRecord.addAssetRecord()
    ctx.body = ctx.resuccess({})
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getAssetRecordsByDay = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      day: { type: 'int', required: true }
    }, query)
    const userNetValues = await ctx.services.assetRecord.getAssetRecordsByDay(data)
    ctx.body = ctx.resuccess({
      list: userNetValues
    })
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getAssetStatistics = async function (ctx) {
  try {
    const result = await ctx.services.assetRecord.getAssetStatistics()
    ctx.body = ctx.resuccess(result)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

// 获取做空做多盈亏统计
exports.getTradeStatisticsByDirection = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      startTime: { type: 'string', required: false },
      endTime: { type: 'string', required: false },
      direction: { type: 'string', required: false }, // 1-只统计做多，2-只统计做空
      reason: { type: 'string', required: false }, // 只统计某个reason
      exactMatch: { type: 'int', required: false } // 1-精准匹配，其他-模糊匹配(以reason为开头)
    }, query)

    const result = await ctx.services.executeRecord.getTradeStatisticsByDirection(data)
    ctx.body = ctx.resuccess(result)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}
exports.deleteAssetRecords = async function (ctx) {
  try {
    const result = await ctx.services.assetRecord.deleteAssetRecords()
    ctx.body = ctx.resuccess(result)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getAssetRecordDetail = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      _id: { type: 'string', required: true }
    }, query)
    const detail = await ctx.services.assetRecord.getAssetRecordDetail(data)
    ctx.body = ctx.resuccess(detail)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.remarkAssetRecord = async function (ctx) {
  const query = ctx.request.body
  try {
    const data = ctx.validateData({
      _id: { required: true, type: 'string' },
      remark: { required: false, type: 'string' },
      withdraw_usdt: { required: false, type: 'int' }
    }, query)
    await ctx.services.assetRecord.remarkAssetRecord(data)
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

// 获取操作统计
exports.countConditionStatistics = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      count: { type: 'int', required: false }
    }, query)
    const result = await ctx.services.executeRecord.countConditionStatistics(data.count || 1000)
    ctx.body = ctx.resuccess(result)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.analysisBtbTest = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      code: { type: 'string', required: true },
      interval: { type: 'string', required: true }
    }, query)
    const result = await ctx.services.btbIndex.analysisBtbTest(data)
    ctx.body = ctx.resuccess(result)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.analysisBtbBuySellTest = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      code: { type: 'string', required: true }
    }, query)
    const result = await ctx.services.btbIndex.analysisBtbBuySellTest(data)
    ctx.body = ctx.resuccess(result)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getQuoteRecordsByDay = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      day: { type: 'int', required: true }
    }, query)
    const userNetValues = await ctx.services.btbIndex.getQuoteRecordsByDay(data)
    ctx.body = ctx.resuccess(userNetValues)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}
exports.reformatQuoteVolumeRecords = async function (ctx) {
  try {
    await ctx.services.btbIndex.reformatQuoteVolumeRecords()
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}
exports.getQuoteVolumeRecordsByPage = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      current: { type: 'int', required: true },
      pageSize: { type: 'int', required: true },
      startTime: { type: 'string', required: false },
      endTime: { type: 'string', required: false },
      modelStr: { type: 'string', required: false }
    }, query)
    let paging = ctx.paging(data.current, data.pageSize)
    // 分页获取
    const result = await ctx.services.btbIndex.getQuoteVolumeRecordsByPage({
      ...data
    }, paging)
    paging.total = result.count
    ctx.body = ctx.resuccess({
      list: result.list.map((v) => {
        const detail = v.detail || {}
        btbAs.getAnalysisMarketInfo(detail)
        detail.countModel1d = {}
        detail.countModel1h = {}
        detail.countModel4h = {}
        detail.countModel15m = {}
        detail.countSumModelInfo = {}
        v.hasError = (detail.errorList && detail.errorList.length > 0)
        detail.errorList = []
        v.detail = detail
        return v
      }),
      page: paging
    })
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getQuoteVolumeRecordDetail = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      _id: { type: 'string', required: true }
    }, query)
    const result = await ctx.services.btbIndex.getQuoteVolumeRecordDetail(data)
    result.detail = result.detail || {}
    btbAs.getAnalysisMarketInfo(result.detail)
    const marketMachine = new MarketMachine({
      marketInfo: result.detail,
      marketInfoList: []
    })
    result.detail = {
      ...result.detail,
      ...marketMachine.getAllFlag()
    }
    ctx.body = ctx.resuccess(result)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getBtbWarnRecordsByPage = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      current: { type: 'int', required: true },
      pageSize: { type: 'int', required: true }
    }, query)
    let paging = ctx.paging(data.current, data.pageSize)
    // 分页获取
    const result = await ctx.services.btbIndex.getBtbWarnRecordsByPage({
      ...data
    }, paging)
    paging.total = result.count
    ctx.body = ctx.resuccess({
      list: result.list.map((v) => {
        return v
      }),
      page: paging
    })
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.getMyBalanceInfoV2 = async function (ctx) {
  try {
    const res = await ctx.services.btbIndex.getMyBalanceInfoV2()
    ctx.body = ctx.resuccess(res)
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

// 平仓
exports.closePositionHYV2 = async function (ctx) {
  const query = ctx.query
  try {
    const data = ctx.validateData({
      code: { type: 'string', required: false }
    }, query)
    await ctx.services.btbIndex.closePositionHYV2(data)
    ctx.body = ctx.resuccess()
  } catch (err) {
    ctx.body = ctx.refail(err)
  }
}

exports.findGoodBtbInMarketV2 = async function (ctx) {
  const btbErrorEmail = await ctx.services.dictionary.getByKey('btbErrorEmail')
  try {
    await ctx.services.btbIndex.findGoodBtbInMarketV2()
    await ctx.services.dictionary.updateByKey('findBtbResult', {
      value: JSON.stringify({
        msg: '成功',
        success: true,
        time: moment().format('YYYY-MM-DD HH:mm:ss')
      })
    })
    // 置为空
    if (btbErrorEmail && btbErrorEmail.value === 'true' && btbErrorEmail.type2 === '1') {
      await ctx.services.dictionary.updateByKey('btbErrorEmail', {
        type2: ''
      })
    }
    ctx.body = ctx.resuccess({})
  } catch (err) {
    await ctx.services.dictionary.updateByKey('findBtbResult', {
      value: JSON.stringify({
        msg: err.msg || err.message || '失败',
        success: false,
        time: moment().format('YYYY-MM-DD HH:mm:ss')
      })
    })
    if (btbErrorEmail && btbErrorEmail.value === 'true' && btbErrorEmail.type2 !== '1') {
      // 置为报警过了
      await ctx.services.dictionary.updateByKey('btbErrorEmail', {
        type2: '1'
      })
      await sendMail(emailUtil.sendErrorEmail({
        userEmail: '673806687@qq.com',
        err
      }))
    }
    ctx.body = ctx.refail(err)
  }
}

exports.buySellBtbHY15mV2 = async function (ctx) {
  const btbErrorEmail = await ctx.services.dictionary.getByKey('btbErrorEmail')
  try {
    const res = await ctx.services.btbIndex.buySellBtbHY15mV2(ctx)
    await ctx.services.dictionary.updateByKey('btbDoneMessage', {
      value: JSON.stringify({
        ...res,
        msg: '成功',
        success: true,
        time: moment().format('YYYY-MM-DD HH:mm:ss')
      })
    })
    // 置为空
    if (btbErrorEmail && btbErrorEmail.value === 'true' && btbErrorEmail.type === '1') {
      await ctx.services.dictionary.updateByKey('btbErrorEmail', {
        type: ''
      })
    }
    ctx.body = ctx.resuccess(res)
  } catch (err) {
    await ctx.services.dictionary.updateByKey('btbDoneMessage', {
      value: JSON.stringify({
        msg: err.msg || err.message || '失败',
        success: false,
        time: moment().format('YYYY-MM-DD HH:mm:ss')
      })
    })
    if (btbErrorEmail && btbErrorEmail.value === 'true' && btbErrorEmail.type !== '1') {
      // 置为报警过了
      await ctx.services.dictionary.updateByKey('btbErrorEmail', {
        type: '1'
      })
      await sendMail(emailUtil.sendErrorEmail({
        userEmail: '673806687@qq.com',
        err
      }))
    }
    ctx.body = ctx.refail(err)
  }
}

exports.preFindGoodBtbInMarket = async function (ctx) {
  const btbErrorEmail = await ctx.services.dictionary.getByKey('btbErrorEmail')
  let result = {}
  try {
    result = await ctx.services.btbIndex.preFindGoodBtbInMarket(ctx)
    await ctx.services.dictionary.updateByKey('preFindBtbResult', {
      value: JSON.stringify({
        ...result,
        msg: '成功',
        success: true,
        time: moment().format('YYYY-MM-DD HH:mm:ss')
      })
    })
    if (result.ifBtbWarn) {
      // 不要提醒了，简直是亏钱的源泉
      // await sendMail(emailUtil.sendBtbAbnormalVolatility({
      //   userEmail: '673806687@qq.com',
      //   list: result.abnormalVolatilityList
      // }))
    }
    // 置为空
    if (btbErrorEmail && btbErrorEmail.value === 'true' && btbErrorEmail.type1 === '1') {
      await ctx.services.dictionary.updateByKey('btbErrorEmail', {
        type1: ''
      })
    }
    ctx.body = ctx.resuccess({})
  } catch (err) {
    await ctx.services.dictionary.updateByKey('preFindBtbResult', {
      value: JSON.stringify({
        msg: err.msg || err.message || '失败',
        success: false,
        time: moment().format('YYYY-MM-DD HH:mm:ss')
      })
    })
    if (btbErrorEmail && btbErrorEmail.value === 'true' && btbErrorEmail.type1 !== '1') {
      // 置为报警过了
      await ctx.services.dictionary.updateByKey('btbErrorEmail', {
        type1: '1'
      })
      await sendMail(emailUtil.sendErrorEmail({
        userEmail: '673806687@qq.com',
        err
      }))
    }
    ctx.body = ctx.refail(err)
  }
}
